package com.zzl.alligator.common.util;

import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzl.alligator.common.constant.ProjectProperties;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 * TODO
 *
 * @author zhouziliang
 * @since 2020/6/27
 */
@Slf4j
public class AddressUtils {

    /**
     * IP地址查询
     */
    public static final String IP_URL = "http://whois.pconline.com.cn/ipJson.jsp";

    /**
     * 未知地址
     */
    public static final String UNKNOWN = "XX XX";

    /**
     * 获取地址
     *
     * @param ip ip
     * @return 地址
     */
    public static String getRealAddressByIp(String ip) {
        String address = UNKNOWN;
        // 内网不查询
        if (IpUtils.internalIp(ip)) {
            return "内网IP";
        }
        ProjectProperties projectProperties = SpringUtil.getBean(ProjectProperties.class);
        if (projectProperties.isAddressEnabled()) {
            try {
                Map<String, Object> param = new HashMap<>(2);
                param.put("ip", ip);
                param.put("json", "true");
                String rspStr = HttpUtil.get(IP_URL, param);
                if (StringUtils.isEmpty(rspStr)) {
                    log.error("获取地理位置异常 {}", ip);
                    return UNKNOWN;
                }
                JSONObject obj = JSONUtil.parseObj(rspStr);
                String region = (String)obj.get("pro");
                String city = (String)obj.get("city");
                return String.format("%s %s", region, city);
            } catch (Exception e) {
                log.error("获取地理位置异常 {}", ip);
            }
        }
        return address;
    }
}
